<template>
  <el-card>
    <h2>ModelOID管理</h2>

    <!-- 查询表单 -->
    <el-form :inline="true" :model="queryForm" class="demo-form-inline">
      <el-form-item label="设备型号">
        <el-select v-model="queryForm.model" placeholder="请选择设备型号" clearable filterable>
          <el-option
            v-for="model in modelList"
            :key="model"
            :label="model"
            :value="model">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onQuery">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
        <el-button type="success" @click="openDialog">新增</el-button>
        <el-button type="info" @click="handleExport" :loading="exportLoading">导出</el-button>
        <el-button type="warning" @click="openImportDialog">导入</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table :data="tableData" style="width: 100%" border>
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="model" label="设备型号" width="150"></el-table-column>
      <el-table-column prop="oid_name" label="OID名称" width="200"></el-table-column>
      <el-table-column prop="oid_value" label="OID值" width="300"></el-table-column>
      <el-table-column prop="descr" label="描述"></el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button type="primary" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryForm.page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryForm.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px">
      <el-form :model="formData" :rules="rules" ref="form" label-width="120px">
        <el-form-item label="设备型号" prop="model">
          <el-input v-model="formData.model" placeholder="请输入设备型号"></el-input>
        </el-form-item>
        <el-form-item label="OID名称" prop="oid_name">
          <el-input v-model="formData.oid_name" placeholder="请输入OID名称"></el-input>
        </el-form-item>
        <el-form-item label="OID值" prop="oid_value">
          <el-input v-model="formData.oid_value" placeholder="请输入OID值"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="descr">
          <el-input 
            v-model="formData.descr" 
            type="textarea" 
            :rows="3"
            placeholder="请输入描述">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog title="导入ModelOID数据" :visible.sync="importDialogVisible" width="500px">
      <el-form :model="importForm" label-width="120px">
        <el-form-item label="选择文件">
          <el-upload
            ref="upload"
            :auto-upload="false"
            :on-change="handleFileChange"
            :file-list="fileList"
            accept=".csv"
            :limit="1">
            <el-button slot="trigger" size="small" type="primary">选择文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传CSV文件</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="导入选项">
          <el-checkbox v-model="importForm.replace_existing">替换已存在的数据</el-checkbox>
        </el-form-item>
        <el-form-item>
          <div class="import-tips">
            <p><strong>CSV文件格式要求：</strong></p>
            <p>1. 支持两种表头格式：</p>
            <p>&nbsp;&nbsp;&nbsp;• 英文格式：ID, Model, OID Name, OID Value, Description</p>
            <p>&nbsp;&nbsp;&nbsp;• 中文格式：ID, 设备型号, OID名称, OID值, 描述</p>
            <p>2. 第一行为表头，从第二行开始为数据</p>
            <p>3. ID列可以为空（新增时自动生成）</p>
            <p>4. 如果选择"替换已存在的数据"，会根据设备型号和OID名称匹配更新</p>
            <p>5. 文件编码必须为UTF-8格式</p>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="importDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleImport" :loading="importLoading">开始导入</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import axios from 'axios'

export default {
  data() {
    return {
      queryForm: {
        model: '',
        page: 1,
        pageSize: 10
      },
      tableData: [],
      total: 0,
      modelList: [],
      dialogVisible: false,
      dialogTitle: '新增ModelOID',
      formData: {},
      submitLoading: false,
      exportLoading: false,
      importDialogVisible: false,
      importLoading: false,
      importForm: {
        replace_existing: false
      },
      fileList: [],
      rules: {
        model: [
          { required: true, message: '请输入设备型号', trigger: 'blur' }
        ],
        oid_name: [
          { required: true, message: '请输入OID名称', trigger: 'blur' }
        ],
        oid_value: [
          { required: true, message: '请输入OID值', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    onQuery() {
      this.queryForm.page = 1
      this.getModelOidList()
    },
    resetQuery() {
      this.queryForm = {
        model: '',
        page: 1,
        pageSize: 10
      };
      this.getModelOidList();
    },
    getModelOidList() {
      axios.get('/pidscloud/modeloid/list', {
        params: this.queryForm
      }).then(response => {
        const { list, total, page, pageSize } = response.data.data
        this.tableData = list
        this.total = total
        this.queryForm.page = page
        this.queryForm.pageSize = pageSize
      })
      .catch(error => {
        console.error('获取ModelOID列表失败:', error);
        this.$message.error('获取数据失败');
      });
    },
    getModelList() {
      axios.get('/pidscloud/modeloid/models')
        .then(response => {
          this.modelList = response.data.data;
        })
        .catch(error => {
          console.error('获取型号列表失败:', error);
        });
    },
    handleSizeChange(val) {
      this.queryForm.pageSize = val
      this.getModelOidList()
    },
    handleCurrentChange(val) {
      this.queryForm.page = val
      this.getModelOidList()
    },
    openDialog() {
      this.dialogTitle = '新增ModelOID'
      this.formData = {}
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogTitle = '编辑ModelOID'
      this.formData = { ...row }
      this.dialogVisible = true
    },
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.submitLoading = true
          const isEdit = !!this.formData.id
          const url = isEdit ? '/pidscloud/modeloid/update' : '/pidscloud/modeloid/add'
          const method = isEdit ? 'put' : 'post'
          
          axios({
            method: method,
            url: url,
            data: this.formData
          }).then(() => {
            this.$message.success(isEdit ? '更新成功' : '新增成功');
            this.dialogVisible = false;
            this.getModelOidList();
            this.getModelList(); // 刷新型号列表
          }).catch(error => {
            console.error('操作失败:', error);
            this.$message.error('操作失败');
          }).finally(() => {
            this.submitLoading = false;
          });
        }
      });
    },
    handleDelete(row) {
      this.$confirm('确定删除该ModelOID信息吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete(`/pidscloud/modeloid/delete/${row.id}`)
          .then(() => {
            this.$message.success('删除成功');
            this.getModelOidList();
            this.getModelList(); // 刷新型号列表
          })
          .catch(error => {
            console.error('删除失败:', error);
            this.$message.error('删除失败');
          });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    handleExport() {
      this.exportLoading = true
      const params = new URLSearchParams()
      if (this.queryForm.model) {
        params.append('model', this.queryForm.model)
      }
      
      window.open(`/pidscloud/modeloid/export?${params.toString()}`)
      
      // 模拟导出完成
      setTimeout(() => {
        this.exportLoading = false
        this.$message.success('导出完成')
      }, 1000)
    },
    openImportDialog() {
      this.importDialogVisible = true
      this.fileList = []
      this.importForm.replace_existing = false
    },
    handleFileChange(file, fileList) {
      this.fileList = fileList
    },
    handleImport() {
      if (this.fileList.length === 0) {
        this.$message.error('请选择要导入的文件')
        return
      }

      this.importLoading = true
      const formData = new FormData()
      formData.append('file', this.fileList[0].raw)
      formData.append('replace_existing', this.importForm.replace_existing)

      axios.post('/pidscloud/modeloid/import', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(response => {
        const data = response.data.data
        this.$message.success(
          `导入完成！新增: ${data.success_count}, 更新: ${data.update_count}, 跳过: ${data.skip_count}`
        )
        this.importDialogVisible = false
        this.getModelOidList()
        this.getModelList()
      }).catch(error => {
        console.error('导入失败:', error)
        const errorMsg = error.response?.data?.message || error.message
        this.$message({
          message: '导入失败: ' + errorMsg,
          type: 'error',
          duration: 8000, // 延长显示时间以便查看详细错误
          showClose: true
        })
      }).finally(() => {
        this.importLoading = false
      })
    }
  },
  mounted() {
    this.getModelOidList();
    this.getModelList();
  }
}
</script>

<style scoped>
.el-form-item {
  margin-bottom: 20px;
}
.pagination-container {
  margin-top: 20px;
  text-align: right;
}
.import-tips {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  font-size: 14px;
  color: #606266;
}
.import-tips p {
  margin: 5px 0;
}
</style>
